package com.zz.framework.core.adapter;


import android.view.ViewGroup;

import com.zz.framework.core.base.BaseUIFragment;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.RecyclerView;


public class FragmentAdapter extends FragmentStatePagerAdapter {
    RecyclerView.RecycledViewPool mPool;
    private List<Fragment> mFragments;
    private List<String> mTitles;
    int position;
    Fragment currentFragment;

    public FragmentAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
        super(fm);
        mFragments = fragments;
        mTitles = titles;
        mPool = new RecyclerView.RecycledViewPool();
    }

    public FragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
        this(fm,fragments,null);
    }


    @NonNull
    public List<Fragment> getFragments() {
        return mFragments;
    }
    @Override
    public Fragment getItem(int position) {
        if(mFragments.get(position) instanceof BaseUIFragment) {
            BaseUIFragment fragment = (BaseUIFragment) mFragments.get(position);
            fragment.setPool(mPool);
            return fragment;
        }else {
            return mFragments.get(position);
        }
    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentFragment = (Fragment) object;
        this.position = position;
        super.setPrimaryItem(container, position, object);
    }

    public int getCurrentPostion(){
        return position;
    }


    public Fragment getCurrentFragment(){
        return currentFragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (mTitles == null||mTitles.size()<=position) {
            return "";
        }
        return mTitles.get(position);
    }
}
